var myBusyIndicator = new WL.BusyIndicator('main',{text : "waiting..."});
var firstLogin = 0;// if first login, skip the read-cache step

(function($){
/*	$("#content").on('pagecreate',function(){	
		alert("pageshow");
		if (firstLogin != 0) {
			readCache();
		}
	});*/
	$("#main").bind("pageshow", function() {
		if (firstLogin != 0) {
			readCache();
		}
	});
	$("#loginBtn").on("click",function(){				
		//myBusyIndicator.show();
		window.page = 0;
		if (loginCheck())
			login();      
//		window.customer.id="13456789098";
//		window.backResult = {};
//		window.backResult.driverInfo = {};
//		window.backResult.driverInfo.id = '123';
//		window.page = 0;
//		window.bookNowState.find({cus_id: window.customer.id}, {})
//		.then(function (data) {
//			if(data.length == 0 || data[0].dri_id == '0') {
//				//there is no book now process recently
//				window.page = 0;
//			} else {
//				var bookNow = data[0].json;
//				window.page = 2;
//				window.backResult.driverInfo.id = bookNow.dri_id;
//				alert("window.backDriInfo.driverInfo.id::" + window.backResult.driverInfo.id);
//			}
//			$.mobile.changePage("view/customer-main.html");
//		})
//		.fail(function (errorObject) {
//		    alert("find fail");
//		});
		
//		$.mobile.changePage("view/customer-main.html");	
	});
	$("#cancelBtn").click(function() {
		//$.mobile.changePage("SmartTest7_17.html");
		$.mobile.changePage("view/info-center.html");
			
	});
	$("#registerBtn").click(function() {

		//alert("111111111");
		$.mobile.changePage("view/register-page.html");
		//$.mobile.changePage("view/customer-main.html");
	});	
})(jQuery);

/**
 * login to the server
 */
function loginCheck() {
	myBusyIndicator.show();
	var name = $('#phone').val();
	var pwd = $('#password').val();
	
	if(!name || !pwd) {
		//busy.hide();
		myBusyIndicator.hide();
		alert("Username and password cannot be empty!");
        return false;
	}	
	if (!checkSubmitMobile()) {
		//busy.hide();
		myBusyIndicator.hide();
		alert("incorrect phone format");
		$("#phone").val("");
		$("#phone").focus();
		return false;
	}	
	return true;
}
function login() {	
	WL.Logger.info("login request begin");
	//alert("login start");
	var username = $('#phone').val();
	var password = $('#password').val();
	//authentication();
	//var username="worklight";
	//var password="worklight";
	var invocationData = {
			adapter : 'stAdp',
			procedure : 'customerLoginReq',
 		    parameters : [{'kind':'c', 'cus_phone': username,'cus_pwd': password}]
			
		};
	//alert("su");
	WL.Client.invokeProcedure(invocationData,{
		//timeout:10000,
		onSuccess : loginSuccess,
		onFailure : loginFailure
	});	
	//var invocationData = {
	//		adapter : "stAdp",
	//		procedure: "getSecretData",
	//		parameters: []
	//};
	
	//WL.Client.invokeProcedure(invocationData, {
	//	onSuccess: getSecretDataOK, 
	//	onFailure: getSecretDataFAIL
	//});
}
/*
function getSecretDataOK(response){
	alert(WL.Client.Push);
	if (WL.Client.Push){
		alert("ok");
		WL.Client.Push.onReadyToSubscribe = function(){
			alert("onReadyToSubscribe");
			
			

			WL.Client.Push.registerEventSourceCallback(
					"myPush", 
					"stAdp", 
					"PushEventSource", 
					pushNotificationReceived);
		};
		
	}
	alert(JSON.stringify(response.invocationResult));
}

function getSecretDataFAIL(response){
	alert(JSON.stringify(response.invocationResult));
}
*/
function loginSuccess(result) {
	//alert("statusCode:" +JSON.stringify(result.invocationResult));
	//alert("responseTime:" + result.invocationResult.responseTime);
	//busy.hide();
	
//	myBusyIndicator.hide();
	
	if(result.invocationResult.status == 0){
		var value = $('#phone').val() + "+" + $('#password').val();
		window.customer.id=$('#phone').val();
		WL.Logger.info("firstLogin: " + firstLogin);
		if (firstLogin == 0) {
			writeCache('username', value);
		}
	//alert("loginsuccess");
		/*if (WL.Client.Push){
		//alert("WL.Client.Push");
		WL.Client.Push.onReadyToSubscribe = function(){
			alert("onReadyToSubscribe");
			
			//$('#SubscribeButton').removeAttr('disabled');
			//$('#UnsubscribeButton').removeAttr('disabled');

			WL.Client.Push.registerEventSourceCallback(
					"myPush", 
					"stAdp", 
					"PushEventSource", 
					pushNotificationReceived);
		};
		
	}
	doSubscribe();*/
	//JSON.stringify(response.invocationResult)
		$.mobile.changePage("view/customer-main.html");
	
	}else if(result.invocationResult.status == 1){
		alert("cusphone or cuspassword  wrong");	
	}else{		
		alert("system error");	
	}
}
	function doSubscribe(){
		alert("doSubscribe");
		WL.Client.Push.subscribe("myPush", {
			onSuccess: doSubscribeSuccess,
			onFailure: doSubscribeFailure
		});
	}

	function doSubscribeSuccess(){
		alert("doSubscribeSuccess");
	}

	function doSubscribeFailure(){
		alert("doSubscribeFailure");
	}
//	
//	$.mobile.changePage("view/customer-main.html");

function loginFailure(result) {
	//alert(result);
	//busy.hide();
	myBusyIndicator.hide();
	alert("login request failure");	
	WL.Logger.error("login request failure");
	
}
function pushNotificationReceived(props, payload){
	alert("pushNotificationReceived invoked");
	alert("props :: " + JSON.stringify(props));
	alert("payload :: " + JSON.stringify(payload));
}
//Open
/*
function openCache(){
	WL.Logger.info("Open cache start");
	var key = "username";	
	myBusyIndicator.show();	
	WL.EncryptedCache.open(key, true, onOpenComplete, onOpenError);

	function onOpenComplete(status){
		WL.Logger.info("Open Complete");
		//alert("OpenComplete");
		myBusyIndicator.hide();
	}
	function onOpenError(status){
		myBusyIndicator.hide();
		WL.Logger.info("Open fail");
		switch(status){
			case WL.EncryptedCache.ERROR_KEY_CREATION_IN_PROGRESS:
				alert("ERROR: KEY CREATION IN PROGRESS");
			break;
		case WL.EncryptedCache.ERROR_LOCAL_STORAGE_NOT_SUPPORTED:
			alert("ERROR: LOCAL STORAGE NOT SUPPORTED");
			break;
		case WL.EncryptedCache.ERROR_NO_EOC:
			alert("ERROR: NO EOC");
			break;
		case WL.EncryptedCache.ERROR_COULD_NOT_GENERATE_KEY:
			alert("ERROR: COULD NOT GENERATE KEY");
			break;
		case WL.EncryptedCache.ERROR_CREDENTIALS_MISMATCH:
			alert("ERROR: CREDENTIALS MISMATCH");
			break;
		default:
			alert("AN ERROR HAS OCCURED. STATUS :: " + status);
		}
	}	
}
*/

// Close
function closeCache(){
	WL.Logger.info("close start");
	WL.EncryptedCache.close(onCloseCompleteHandler, onCloseFailureHandler);
}
function onCloseCompleteHandler(status){
	//alert("Encrypted cache closed successfuly");
	WL.Logger.info("close Complete");
}
function onCloseFailureHandler(status){
	alert("Could not close Encrypted cache");
	WL.Logger.info("close not complete");
}

// Destroy
function destroyCache(){
	WL.Logger.info("destroy start");
	WL.EncryptedCache.destroy(onDestroyCompleteHandler, onDestroyErrorHandler);
	//alert("Encrypted cache destroyed");
}
function onDestroyCompleteHandler(status){
	firstLogin = 0;
	WL.Logger.info("destroy Complete");
	//alert("Encrypted cache destroyed");
}
function onDestroyErrorHandler(status){
	alert("Error destroying Encrypted cache");
	WL.Logger.info("destroy not Complete");
}

// read cache
function readCache() {
	WL.Logger.info("read start");
	var username, password;
	
	WL.Logger.info("Open cache start");
	var key = "username";	
	myBusyIndicator.show();	
	WL.EncryptedCache.open(key, true, onOpenComplete, onOpenError);

	function onOpenComplete(status){
		WL.Logger.info("Open Complete");
		WL.EncryptedCache.read(key, onDecryptReadSuccess, onDecryptReadFailure);
		function onDecryptReadSuccess(value){
			//alert("onReadSuccess");
			WL.Logger.info("read Complete");
			var tmp = value.split("+");
			username = tmp[0];
			password = tmp[1];
			submitLogin(username, password);	
			closeCache();
		}
		function onDecryptReadFailure(status){
			alert("Encrypted cache closed, reading failed");
			closeCache();
			WL.Logger.info("read not Complete");
		}
		//alert("OpenComplete");
		myBusyIndicator.hide();
	}
	function onOpenError(status){
		myBusyIndicator.hide();
		WL.Logger.info("Open fail");
		switch(status){
			case WL.EncryptedCache.ERROR_KEY_CREATION_IN_PROGRESS:
				alert("ERROR: KEY CREATION IN PROGRESS");
			break;
		case WL.EncryptedCache.ERROR_LOCAL_STORAGE_NOT_SUPPORTED:
			alert("ERROR: LOCAL STORAGE NOT SUPPORTED");
			break;
		case WL.EncryptedCache.ERROR_NO_EOC:
			alert("ERROR: NO EOC");
			break;
		case WL.EncryptedCache.ERROR_COULD_NOT_GENERATE_KEY:
			alert("ERROR: COULD NOT GENERATE KEY");
			break;
		case WL.EncryptedCache.ERROR_CREDENTIALS_MISMATCH:
			alert("ERROR: CREDENTIALS MISMATCH");
			break;
		default:
			alert("AN ERROR HAS OCCURED. STATUS :: " + status);
		}
	}	
}

// write cache
function writeCache(key, value){	
	WL.Logger.info("write start");
	
	WL.Logger.info("Open cache start");
	var key = "username";	
	myBusyIndicator.show();	
	WL.EncryptedCache.open(key, true, onOpenComplete, onOpenError);

	function onOpenComplete(status){
		WL.Logger.info("Open Complete");
		
		//alert("write : " + value);	
		WL.EncryptedCache.write(key, value, onWriteSuccess, onWriteFailure);
		function onWriteSuccess(status){
			
			WL.Logger.info("write Complete");
			closeCache();
			//alert("Succesfully encrypted into cache.");
			firstLogin = 1;
		}
		function onWriteFailure(status){
			WL.Logger.info("write not Complete");
			closeCache();
			if (status == WL.EncryptedCache.ERROR_EOC_CLOSED) 
				alert("Encrypted cache closed, write failed. error code= "+ status);
		}
		
		//alert("OpenComplete");
		myBusyIndicator.hide();
	}
	function onOpenError(status){
		myBusyIndicator.hide();
		WL.Logger.info("Open fail");
		switch(status){
			case WL.EncryptedCache.ERROR_KEY_CREATION_IN_PROGRESS:
				alert("ERROR: KEY CREATION IN PROGRESS");
			break;
		case WL.EncryptedCache.ERROR_LOCAL_STORAGE_NOT_SUPPORTED:
			alert("ERROR: LOCAL STORAGE NOT SUPPORTED");
			break;
		case WL.EncryptedCache.ERROR_NO_EOC:
			alert("ERROR: NO EOC");
			break;
		case WL.EncryptedCache.ERROR_COULD_NOT_GENERATE_KEY:
			alert("ERROR: COULD NOT GENERATE KEY");
			break;
		case WL.EncryptedCache.ERROR_CREDENTIALS_MISMATCH:
			alert("ERROR: CREDENTIALS MISMATCH");
			break;
		default:
			alert("AN ERROR HAS OCCURED. STATUS :: " + status);
		}
	}	
	
}

/**
 * check phone number
 */

function checkSubmitMobile() {
	if (!$("#phone").val().match(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/)) {
		return false;
	}
	return true;
}


